<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/27
 * Time: 18:56
 */

namespace app\lib\Exception;


use think\exception\Handle;
use think\Log;
use think\Request;

class ExceptionHandler extends Handle
{
    private $stateCode;
    private $info;
    private $errorCode;

    public function render(\Exception $ex)
    {
        if ($ex instanceof BaseException) {
            //    用户异常，不记录
            $this->stateCode =$ex->stateCode;
            $this->info =$ex->info;
            $this->errorCode =$ex->errorCode;
        } else {
            //    服务器异常，记录日志
            if (config('app_debug')) {
                //    开发模式 直接返回，不记录日志
                return parent::render($ex);
            } else {
                //    生产模式，记录日志
                $this->info = '服务器错误';
                $this->errorCode = 999;
                $this->stateCode = 500;
                $this->recordErrorLog($ex);
            }
        }

        $request = Request::instance();

        $result = [
            'info' =>$this->info,
            'errorCode'=>$this->errorCode,
            'request_url'=> $request->url()
        ];
            return json($result,$this->stateCode);

    }

    private function recordErrorLog(\Exception $ex){
        // 初始化日志
        Log::init([
            'type'  => 'File',
            // 日志保存目录
            'path'  => LOG_PATH,
            // 日志记录级别
            'level' => ['error']
        ]);

        Log::record($ex->getMessage(),'error');
    }

}